package com.yds.dubbo.common;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;

/**
 * @author liuhongzhen
 * @date 2023/3/24 14:20
 */
public class ZkTools {

    private static String zookeeperHost = System.getProperty("zookeeper.address","127.0.0.1");

    private static CuratorFramework client;

    public static void main(String[] args) throws Exception {
        generateDubboProperties();
    }


    public static void generateDubboProperties(){

        client = CuratorFrameworkFactory.newClient(zookeeperHost + ":2181",60 * 1000, 60 * 1000,
                new ExponentialBackoffRetry(100,2));

        client.start();

        generateDubboPropertiesForGlobal();
        generateDubboPropertiesForApp();
    }


    public static void generateDubboPropertiesForGlobal(){
        String str = "dubbo.registry.address=zookeeper://" + zookeeperHost + ":2181\n" +
                "dubbo.metadata-report.address=zookeeper://" + zookeeperHost + ":2181\n" +
                "dubbo.protocol.port=-1\n" +
                "dubbo.registry.simplified=true\n";

        System.out.println(str);


        try{
            String path = "/dubbo/config/dubbo/dubbo.properties";

            if (client.checkExists().forPath(path) == null){
                client.create().creatingParentContainersIfNeeded().forPath(path);
            }

            setData(path, str);
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    public static void generateDubboPropertiesForApp() {
        String str = "dubbo.consumer.timeout=6666\n" +
                "dubbo.application.qos.port=33333\n" +
                "dubbo.reference.org.apache.dubbo.samples.configcenter.api.DemoService.timeout=9999";

        System.out.println(str);

        try {
            String path = "/dubbo/config/configcenter-provider/dubbo.properties";
            if (client.checkExists().forPath(path) == null) {
                client.create().creatingParentsIfNeeded().forPath(path);
            }
            setData(path, str);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void createNode(String path) throws Exception {
        client.create().forPath(path);
    }

    private static void deleteNode(String path) throws Exception {
        client.delete().forPath(path);
    }

    private static void setData(String path, String data) throws Exception {
        client.setData().forPath(path, data.getBytes());
    }

}
